package cn.cstech.aijia.ui;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.RelativeLayout;

import cn.cstech.aijia.R;
import cn.cstech.aijia.appupgrade.AppUpdateManager;
import cn.cstech.aijia.ui.base.BaseFragmentActivity;
import cn.cstech.aijia.ui.base.fragments.MainFragment;
import cn.cstech.aijia.ui.base.fragments.MineFragment;
import cn.cstech.aijia.ui.base.fragments.SampleFragment;
import cn.cstech.aijia.ui.base.fragments.ServiceFragment;
import cn.cstech.aijia.ui.base.fragments.ShopMallFragment;
import cn.cstech.aijia.ui.base.utils.SPUtils;
import cn.cstech.aijia.ui.base.utils.LocalUtils;
import cn.cstech.aijia.ui.user.LoginActivity;

/**
 * Created with Android Studio.
 * Title:SampleTabFragment
 * Description:
 * Copyright:Copyright (c) 2014
 * Company:中国平安健康保险有限公司
 * Author:Alice
 * Date:15/8/24
 * Time:下午2:31
 * Version 1.0
 */

public class MainActivity extends BaseFragmentActivity {
    private final static String TAG = MainActivity.class.getSimpleName();
    public final static int TAB_NUM = 4;
    public static final int TAB_1 = 0;
    public static final int TAB_2 = 1;
    public static final int TAB_3 = 2;
    public static final int TAB_4 = 3;
//    public static final int TAB_5 = 5;
    private ViewPager vp_home;
    private Button btn_item_new_msg;

    private int mClickBackCount = 0;
    private AppUpdateManager mAppUpdateManager;
    private RelativeLayout rl_tabs[] = new RelativeLayout[TAB_NUM];
//    private AdvatisementFragment mAdFragment;
//    private MyHandler mHandler;
    private RelativeLayout mFloatLayout;

    // ----- 以下为Activity生命周期方法

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        addTitleBar = false;

        setContentView(R.layout.ac_main);

        initViews();
//        mHandler = new MyHandler(this);
//        initFragments();
        checkUpdateApp();

        initTabs();
        initViewPager();

        int defaultTabIndex = getTabIndex(getIntent());
        if (-1 != defaultTabIndex) {
            clickTab(defaultTabIndex);
        }

//        startActivity(new Intent(this, LoginActivity.class));
    }

    @Override
    public void handleMessage(Message msg) {
        switch (msg.what) {
            case AppUpdateManager.MSG_HIDE_UPATE_DLG:
                if (mAppUpdateManager != null) {
                    mAppUpdateManager.dismissProgressDialog();
                }
                LocalUtils.showToast(this, (String) msg.obj);
                break;
            case AppUpdateManager.MSG_HAS_UPDATE:
                if (mAppUpdateManager != null && !isFinishing()) {
                    mAppUpdateManager.dismissProgressDialog();
                    mAppUpdateManager.showUpdateInfoDialog(this);
                }
                break;
        }
    }

    private void initViews(){
        vp_home = (ViewPager)findViewById(R.id.vp_home);
        btn_item_new_msg = (Button)findViewById(R.id.btn_item_new_msg);
//        btn_item_pharmacy = (Button)findViewById(R.id.btn_item_pharmacy);
    }

    @Override
    public void onResume() {
        super.onResume();

//        checkIn();
    }

//    private LoginGiftFragment mGiftFragment;
//    public void checkIn() {
//        if (SharedPreferenceUtil.CheckDay(MainActivityNew.this)
//                || SharedPreferenceUtil.CheckCurrentActDay(MainActivityNew.this)) {
//            NetManager.getInstance(getApplicationContext()).doCheckInAndGetAct(
//                    new OnResponseListener<CheckinAndActResult>() {
//
//                        @Override
//                        public void onInernError(int errorCode, String errorMessage) {
//
//                        }
//
//                        @Override
//                        public void onComplete(boolean isOK, CheckinAndActResult result, int errorCode, String errorMsg) {
//                            if (null != result) {
////								startGift(result.checkInGift);
//                                if (null != result.activityStatusInfo
//                                        && SharedPreferenceUtil.CheckCurrentActDay(MainActivityNew.this)
//                                        ) {
//                                    if (MainActivityNew.this != null
//                                            && ((PriDocApplication) getApplication())
//                                            .isActivityOpened(MainActivityNew.class)) {
//                                        LogUtils.d("CheckActDay" + isOK);
//                                        //判断活动是否存在
//                                        if (result.activityStatusInfo.isOnActivate
//                                                && null != result.activityStatusInfo.linkUrl
//                                                && !TextUtils.isEmpty(result.activityStatusInfo.linkUrl)) {
//                                            ExecuteSchemeUtil.gotoFullScreenLink(MainActivityNew.this,
//                                                    result.activityStatusInfo.linkUrl);
////											if(result.activityStatusInfo.isOnActivate){
//                                            SharedPreferenceUtil.setCurrentActDay(MainActivityNew.this);
////											}
//                                            //只进行checkingift检测，并处理，不弹出页面
//                                            if (null != result.checkInGift && result.checkInGift.todayCredits > 0) {
//                                                AndroidMusicPool.getInstance(MainActivityNew.this).playScoreBeep();
//                                                SharedPreferenceUtil.setCheckInDayInt(MainActivityNew.this);
//                                            }
//                                        } else if (null != result.checkInGift) {
//                                            showCheckInDay(result.checkInGift);
//                                        }
//                                    }
//                                } else if (null != result.checkInGift) {
//                                    showCheckInDay(result.checkInGift);
//                                }
//                            }
//                        }
//                    });
//
//        }
//    }

    /** 每日奖励界面
     */
//    private void showCheckInDay(CheckInGift checkInGift){
//        if(MainActivityNew.this != null  &&
//                ((PriDocApplication)getApplication()).isActivityOpened(MainActivityNew.class)) {
//            LogUtils.d("CheckInDay ok");
//
//            mGiftFragment = (LoginGiftFragment) getSupportFragmentManager().findFragmentByTag(LoginGiftFragment.class.getSimpleName());
//            if (null == mGiftFragment && checkInGift != null) {
//                mGiftFragment = LoginGiftFragment.newInstance(checkInGift);
//            }
//            if(mGiftFragment != null && checkInGift.todayCredits > 0) {
//                AndroidMusicPool.getInstance(MainActivityNew.this).playScoreBeep();
//                startGift(checkInGift);
//                SharedPreferenceUtil.setCheckInDayInt(MainActivityNew.this);
//            }
//        }
//    }

//    private void startGift(CheckInGift checkInGift) {
//        Intent intent = new Intent(MainActivityNew.this, LoginGiftActivity.class);
//        intent.putExtra(LoginGiftFragment.LOGINGIFTFRAGMENT_ARG, checkInGift);
//        int count = SharedPreferenceUtil.getUnfinishTaskCount(getApplication());
//        long score = SharedPreferenceUtil.getScore(getApplication());
//        intent.putExtra(LoginGiftFragment.LOGINGIFTFRAGMENT_POINT, score);
//        intent.putExtra(LoginGiftFragment.LOGINGIFTFRAGMENT_TASKS, count);
//        startActivity(intent);
//    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

//    private void initFragments() {
//        FragmentTransaction fragmentTransaction = getSupportFragmentManager()
//                .beginTransaction();
//
//        String url = SharedPreferenceUtil.getAdUrl(this);
//        if (SharedPreferenceUtil.isAdValid(this) && url != null
//                && SharedPreferenceUtil.isAdImageReady(this)) {
//            mAdFragment = (AdvatisementFragment) getSupportFragmentManager()
//                    .findFragmentByTag(
//                            AdvatisementFragment.class.getSimpleName());
//            if (null == mAdFragment) {
//                mAdFragment = new AdvatisementFragment();
//                Bundle b = new Bundle();
//                MediatorEntity med = new MediatorEntity();
//                med.setAd(true);
//                med.setImageUrl(url);
//                b.putSerializable(
//                        com.pingan.papd.common.Constants.EXTRA_DATA_OBJECT, med);
//                mAdFragment.setArguments(b);
//            }
//            fragmentTransaction.add(R.id.main_layout, mAdFragment);
//        } else {
//            SharedPreferenceUtil.setAdReady(this);
//        }
//        fragmentTransaction.commitAllowingStateLoss();
//    }

    // ----- 以下为底部Tab及Viewpager内容的切换逻辑 -----

    private void initViewPager() {
        HomeTabPageAdapter homeTabPageAdapter = new HomeTabPageAdapter(getSupportFragmentManager());
        vp_home.setAdapter(homeTabPageAdapter);
        vp_home.setOffscreenPageLimit(1);
        vp_home.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset,
                                       int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int idx) {
                // 点击Tab时，有必要的处理相关的逻辑
                switch (idx) {
                    case TAB_1:
                        vp_home.setOffscreenPageLimit(TAB_NUM);
                        break;
                    case TAB_2: // 消息
                        vp_home.setOffscreenPageLimit(TAB_NUM);
                        break;
                    case TAB_3:
                        vp_home.setOffscreenPageLimit(TAB_NUM);
                        break;
                    case TAB_4:
                        vp_home.setOffscreenPageLimit(TAB_NUM);
                        break;
//                    case TAB_5:
//                        vp_home.setOffscreenPageLimit(4);
//                        break;
                    default:
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
    }

    private void initTabs() {
        rl_tabs[0] = (RelativeLayout) findViewById(R.id.rl_tab_1);
        rl_tabs[1] = (RelativeLayout) findViewById(R.id.rl_tab_2);
        rl_tabs[2] = (RelativeLayout) findViewById(R.id.rl_tab_3);
        rl_tabs[3] = (RelativeLayout) findViewById(R.id.rl_tab_4);
//        rl_tabs[4] = (RelativeLayout) findViewById(R.id.rl_tab_3);
        for (int idx = 0; idx < TAB_NUM; idx++) {
            final int idxf = idx;
            rl_tabs[idx].setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    clickTab(idxf);
                }
            });
        }
        rl_tabs[0].setSelected(true);
    }

    private void clickTab(int curIdx) {
        if (curIdx == vp_home.getCurrentItem())
            return;

        // 切换Fragment
        vp_home.setCurrentItem(curIdx, false);

        // Tab背景状态变更
        for (int idx = 0; idx < TAB_NUM; idx++) {
            if (idx == curIdx) {
                rl_tabs[idx].setSelected(true);
            } else {
                rl_tabs[idx].setSelected(false);
            }
        }
    }

    class HomeTabPageAdapter extends FragmentPagerAdapter {
        public HomeTabPageAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int idx) {
            // 走新建Fragment流程
            Bundle bundle = new Bundle();
            Fragment fragment = null;
            switch (idx) {
                case TAB_1:
                    fragment = new MainFragment();
                    break;
                case TAB_2:
                    fragment = new ServiceFragment();
                    break;
                case TAB_3:
                    fragment = new ShopMallFragment();
                    break;
                case TAB_4:
                    fragment = new MineFragment();
                    break;
                default:
                    fragment = new SampleFragment();
                    bundle.putString("c", idx + "");
                    fragment.setArguments(bundle);
                    break;
            }

            return fragment;
        }

        @Override
        public int getCount() {
            return TAB_NUM;
        }
    }

    // ************************CHECK APP UPDATE BEGIN************************************//
    private void checkUpdateApp(boolean isManual) {
        mAppUpdateManager = new AppUpdateManager(mUIHandler);
        mAppUpdateManager.checkUpdate(this, isManual);
    }

    private void checkUpdateApp() {
        checkUpdateApp(false);
    }
    // ************************CHECK APP UPDATE END************************************//

    @Override
    protected void onStart() {
        super.onStart();
    }

    // ----- 以下为两次确认退出 -----

    private Runnable r_exit_confirm_reset_counter = new Runnable() {
        @Override
        public void run() {
            mClickBackCount = 0;
        }
    };
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (event != null && event.getAction() == KeyEvent.ACTION_UP
                && keyCode == KeyEvent.KEYCODE_BACK) {
            if (mClickBackCount == 0) {
                LocalUtils.showToast(this, R.string.back_twice_exit);
                mUIHandler.removeCallbacks(r_exit_confirm_reset_counter);
                mUIHandler.postDelayed(r_exit_confirm_reset_counter, 3 * 1000);
                mClickBackCount++;
            } else {
                finish();
            }
            return true;
        }
        return super.onKeyUp(keyCode, event);
    }

    // ----- 以下为消息更新逻辑 -----
//    public void removeAd() {
//        FragmentTransaction fragmentTransaction = getSupportFragmentManager()
//                .beginTransaction();
//        fragmentTransaction
//                .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
//        fragmentTransaction.remove(mAdFragment);
//        fragmentTransaction.commitAllowingStateLoss();
//
//    }

    private void showNewMsgCount(int count) {
        if (count <= 0) {
            btn_item_new_msg.setVisibility(View.GONE);
            return;
        }
        btn_item_new_msg.setVisibility(View.VISIBLE);
        if (count > 99) {
            btn_item_new_msg.setText("...");
        } else {
            btn_item_new_msg.setText(String.valueOf(count));
        }
    }

    public Intent newIntent = null;
    public boolean isMsgCurrent = false;

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        newIntent = intent;
        int tabidx = getTabIndex(intent);
        clickTab(tabidx);
    }

    public void checkTab(int i) {
        clickTab(i);
    }
    /**
     *
     * @param intent
     * @return if intent is null return -1;
     */
    private int getTabIndex(Intent intent) {
        return null == intent ? -1 : intent.getIntExtra(SPUtils.EXTRA_MAIN_PAGE_INDEX, -1);
    }


    public int getTabNum(){
        return vp_home != null ?vp_home.getCurrentItem() : - 1;
    }

    public void setPageLimit(int count) {
        vp_home.setOffscreenPageLimit(count);
    }
}
